/************************************************************************/
/*    Author: Scott Bevin                                               */
/************************************************************************/

#include "QuadTree.h"

namespace XF
{
	QuadTree::QuadTree(float x, float y, float w, float h, unsigned int targetObjects, unsigned int maxDepth)
	{
		mRootNode = new QuadTreeNode(NULL, 0, x, y, w, h);
		mRootNode->MaxDepth(maxDepth);
		mRootNode->TargetObjects(targetObjects);

		mManObjNode = NULL;

		mRenderingTree = false;
	}

	QuadTree::~QuadTree()
	{
		delete mRootNode;
	}

	void QuadTree::AddTreeToOgre()
	{
		if(mManObjNode)
		{
			mOgreManager->getRootSceneNode()->removeChild(mManObjNode);
			delete mManObjNode;
		}

		Ogre::ManualObject *manObj = mOgreManager->createManualObject("QuadTree");
		mManObjNode = mOgreManager->getRootSceneNode()->createChildSceneNode("QuadTree_Node");

		Ogre::MaterialPtr manObjMaterial = Ogre::MaterialManager::getSingleton().create("QuadTreeMaterial", "debugger");
		manObjMaterial->setReceiveShadows(false);
		manObjMaterial->getTechnique(0)->setLightingEnabled(true);
		manObjMaterial->getTechnique(0)->getPass(0)->setDiffuse(1, 1, 1, 1);
		manObjMaterial->getTechnique(0)->getPass(0)->setAmbient(0, 0, 1);
		manObjMaterial->getTechnique(0)->getPass(0)->setSelfIllumination(0, 0, 1);

		manObj->begin("QuadTreeMaterial", Ogre::RenderOperation::OT_LINE_LIST);

		mRootNode->Render(manObj);

		manObj->end();

		mManObjNode->attachObject(manObj);
	}

	void QuadTree::Update(double dT)
	{
		mRootNode->CollideAllBodies();

		if(mRenderingTree && QuadTreeNode::TreeStructureChangedThisFrame())
		{
			AddTreeToOgre();

			QuadTreeNode::ResetTreeStructureChangedBool();
		}
	}
}